package com.mooc.servlet;

import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class ServletFactory {
    private static Map<String,Servlet> servletMap=new HashMap<>();
    static {
    //读取配置文件
    Properties properties = new Properties();
    try {
        //获取所有的配置信息，遍历并创建对象存入map中
        properties.load(new FileReader("servlet.properties"));
        Set<Map.Entry<Object, Object>> entries = properties.entrySet();
        for (Map.Entry<Object, Object> e : entries) {
            String key = (String) e.getKey();
            String value = (String) e.getValue();
            Object o = Class.forName(value).newInstance();
            servletMap.put(key,(Servlet) o);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException exception) {
        exception.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}
    public static Servlet getServlet(String url){
        Servlet servlet=servletMap.get(url);
        if (servlet==null){
            return servletMap.get("/default");
        }
        return servlet;
    }
}
